package com.zx._09_架构.rpc演变过程.rpc_07;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.zx.common.entity.UserRpcDto;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;

public class HessionUtil {

    public static void main(final String[] args) {
        UserRpcDto dto = new UserRpcDto(1L, "Tom");
        final byte[] serialize = HessionUtil.serialize(dto);

        HessionUtil.serializeJDK(dto);
        System.out.println(Arrays.toString(serialize));

        dto = (UserRpcDto) HessionUtil.deserialize(serialize);
        System.out.println(dto);

    }


    public static byte[] serialize(final Object o) {
        try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ) {
            final Hessian2Output output = new Hessian2Output(baos);
            output.writeObject(o);
            output.flush();

            final byte[] bytes = baos.toByteArray();
            System.out.println("hessian len=" + bytes.length);
            output.close();
            return bytes;
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // JDK的序列化实现方式，数据长度远大于hessian
    public static byte[] serializeJDK(final Object o) {
        try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                final ObjectOutputStream output = new ObjectOutputStream(baos);
        ) {
            output.writeObject(o);
            output.flush();
            final byte[] bytes = baos.toByteArray();
            System.out.println("jdk len=" + bytes.length);
            return bytes;
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static Object deserialize(final byte[] bytes) {
        try (final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ) {
            final Hessian2Input output = new Hessian2Input(bais);
            final Object object = output.readObject();
            output.close();
            return object;
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
